package com.yyw.foodie.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yyw.foodie.bo.orders.OrderItemDto;
import com.yyw.foodie.mapper.ItemsSpecMapper;
import com.yyw.foodie.pojo.ItemsSpecEntity;
import com.yyw.foodie.service.ItemsSpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 商品规格 每一件商品都有不同的规格，不同的规格又有不同的价格和优惠力度，规格表为此设计 服务实现类
 * </p>
 *
 * @author yiyw
 * @since 2021-05-22
 */
@Service
public class ItemsSpecServiceImpl extends ServiceImpl<ItemsSpecMapper, ItemsSpecEntity> implements ItemsSpecService {

    @Autowired
    private ItemsSpecMapper itemsSpecMapper;

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public OrderItemDto getItemByPay(String itemId) {
        OrderItemDto itemDto = itemsSpecMapper.selectItemByPay(itemId);
        return itemDto;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public Boolean minusStock(String skuId, Integer buyCount) {
        synchronized (ItemsSpecService.class) {
            UpdateWrapper<ItemsSpecEntity> updateWrapper = new UpdateWrapper<>();
            // 此处通过加乐观锁的机制  库存要大于等于即将要扣除的库存，才能保证商品不会被超卖
            updateWrapper.lambda().setSql("stock = stock - " + buyCount).eq(ItemsSpecEntity::getId, skuId)
                    .ge(ItemsSpecEntity::getStock, buyCount);
            boolean result = update(updateWrapper);
            return result;
        }
    }
}
